package examples.base;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sim.core.annotation.Table;
import sim.core.dbrecord.DbUtils;
import sim.core.dbrecord.Page;
import sim.core.utils.StringUtils;

public class BaseService<T> {
	private Class<T> clazz;

	@SuppressWarnings("unchecked")
	public BaseService() {
		// 使用反射技术得到T的真实类型
		this.clazz = (Class<T>) ((ParameterizedType) this.getClass()//
				.getGenericSuperclass()) // 获取当前new的对象的 泛型的父类 类型
						.getActualTypeArguments()[0];// 获取第一个类型参数的真实类型
		System.out.println("=========>" + clazz + "<===========");
	}

	public T findById(Object id) {
		String sql = String.format("SELECT * FROM %s WHERE id=?", getTableName());
		Object[] params = { id };
		return DbUtils.queryForBean(sql, params, clazz);
	}

	public Long insert(T bean) {
		return DbUtils.insert(bean);
	}

	public Long update(T bean) {
		return DbUtils.update(bean);
	}

	public Long delect(Long id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return delect(params);
	}

	public Long delect(Map<String, Object> params) {
		return DbUtils.delete(getTableName(), params);
	}

	public List<T> findAll() {
		String sql = String.format("SELECT * FROM %s", getTableName());
		return DbUtils.queryForList(sql, new Object[] {}, clazz);
	}

	public long count() {
		String sql = String.format("SELECT COUNT(*) FROM %s", getTableName());
		return DbUtils.count(sql, null);
	}

	public long count(String where, Object[] params) {
		String sql = String.format("SELECT COUNT(*) FROM %s %s", getTableName(), where != null ? where : "");
		return DbUtils.count(sql, params);
	}

	public T find(Map<String, Object> params) {
		return DbUtils.queryForBean(params, clazz);
	}

	public Map<String, Object> findForMap(String sql, Object[] params) {
		return DbUtils.queryForMap(sql, params);
	}

	public List<T> findForList(String where, Object[] params) {
		String sql = String.format("SELECT * FROM %s %s", getTableName(), where != null ? where : "");
		return DbUtils.queryForList(sql, params, clazz);
	}

	public List<Map<String, Object>> findForListMap(String where, Object[] params) {
		String sql = String.format("SELECT * FROM %s %s", getTableName(), where != null ? where : "");
		return DbUtils.queryForList(sql, params);
	}

	public Page findForPage(String where, Object[] params, Page page) {
		String sql = String.format("SELECT * FROM %s %s", getTableName(), where != null ? where : "");
		return DbUtils.queryForPage(sql, params, page);
	}

	/**
	 * 获取要查询的表名
	 * 
	 * @author Feny
	 * @date 2018年5月22日下午2:32:22
	 * @return
	 */
	private String getTableName() {
		String table = clazz.getAnnotation(Table.class).value();
		if (clazz.isAnnotationPresent(Table.class) && StringUtils.isNotBlank(table)) {
			return table;
		}
		char[] charArray = clazz.getSimpleName().toCharArray();
		charArray[0] += 32;
		return String.valueOf(charArray);
	}
}
